package com.stedu.controller;
//备份


import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.stedu.bean.Owner;
import com.stedu.bean.RespBean;
import com.stedu.config.DataListenr;
import com.stedu.exception.SteduException;
import com.stedu.mapper.OwnerMapper;
import com.stedu.service.OwnerService;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/admin/owner")
public class OwnerController {

    @Autowired
    private OwnerService ownerService;
    @Autowired
    private OwnerMapper ownerMapper;
    @Value("${stedu.picUpdown}")
    private String picUpdown;
    @GetMapping
    protected RespBean selectByPage(@RequestParam(value = "pageNum") Integer pageNum, @RequestParam(value = "oname",defaultValue = "") String oname, @RequestParam(value = "ophone",defaultValue = "") String ophone) throws SQLException {
        if (pageNum==null){
            pageNum = 1;
        }
        PageHelper.startPage(pageNum, 5);
        List<Owner> oldmanList = ownerService.selectByOnameAndOphone(oname,ophone);
        PageInfo<Owner> pageInfo = new PageInfo<>(oldmanList);
        return RespBean.ok("查询成功",pageInfo);
    }


    @PostMapping
    public RespBean insert(@Validated @RequestBody Owner owner) throws SteduException {
        //添加
        if (ownerService.insert(owner)) {
             return RespBean.ok("添加成功~~~");
        } else {
            return RespBean.error("添加失败，请重新添加");
        }
    }

    @DeleteMapping("/{oid}")
    public RespBean delete(@PathVariable("oid") Integer oid) throws SteduException {
        if (ownerService.delete(oid)) {
            return RespBean.ok("删除成功~~~");
        } else {
            return RespBean.error("删除失败，请重新删除");
        }
    }

    @PutMapping
    public RespBean update(@Validated @RequestBody Owner owner) throws SteduException {
        if (ownerService.update(owner)) {
            return RespBean.ok("修改成功~~~");
        } else {
            return RespBean.error("修改失败，请重新修改");
        }
    }


    @GetMapping("/{oid}")
    public RespBean selectByOid(@PathVariable("oid") Integer oid) {
        Owner d = ownerService.selectByOid(oid);
        return RespBean.ok("", d);
    }
    @GetMapping("/export")
    public void down(HttpServletResponse response) throws IOException {
        // 查询所有病人信息
        List<Owner> patientsExport = ownerService.selectByOnameAndOphone(null, null);
        // 创建文件保存目录
        Path dir = Paths.get(picUpdown);
        if (!Files.exists(dir)) {
            Files.createDirectories(dir);
        }
        // 构建文件名
        String fileName = "设备信息_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss")) + ".xlsx";
        Path targetFile = dir.resolve(fileName);
        // 使用EasyExcel写出数据到Excel文件
        EasyExcel.write(targetFile.toFile(), Owner.class)
                .sheet("设备信息表")
                .doWrite(patientsExport);
        // 设置响应头
        response.setContentType("application/octet-stream");
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + encodedFileName);
        // 直接通过响应输出文件内容
        try (InputStream is = new FileInputStream(targetFile.toFile());
             OutputStream os = response.getOutputStream()) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
            os.flush();
        } catch (IOException e) {
            // 处理异常
            throw new RuntimeException("文件写入或读取失败", e);
        }
    }

    //文件导入
    @RequestMapping("/importExcel")
    @ResponseBody
    public Object upload(@RequestParam("file") MultipartFile file) throws IOException {
        DataListenr dataListener = new DataListenr(ownerMapper);
        // 创建文件保存目录
        Path dir = Paths.get(picUpdown);
        if (!Files.exists(dir)) {
            Files.createDirectories(dir);
        }
        // 构建文件名
        String fileName = "设备信息_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss")) + ".xlsx";
        Path targetFile = dir.resolve(fileName);
        // 保存文件
        try (var inputStream = file.getInputStream()) {
            Files.copy(inputStream, targetFile);
        }
        // 读取Excel数据并存入数据库
        EasyExcel.read(file.getInputStream(), Owner.class, dataListener).sheet().doRead();
        return "文件已上传并处理完成";
    }
}
